﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace AyFrame.Common
{
    public class Utils
    {
        #region MD5加密
        /// <summary>
        /// md5加密（默认UTF-8）
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string MD5(string pwd)
        {
            return MD5(pwd, Encoding.UTF8);
        }
        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string MD5(string pwd, Encoding encoding)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = encoding.GetBytes(pwd);
            byte[] md5data = md5.ComputeHash(data);
            md5.Clear();
            string str = "";
            for (int i = 0; i < md5data.Length; i++)
            {
                str += md5data[i].ToString("x").PadLeft(2, '0');
            }
            return str;
        }

        public static string MD5_File(string filePath)
        {
            if (!File.Exists(filePath)) return "";
            byte[] md5data = new byte[0];
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                md5data = md5.ComputeHash(fs);
            }
            string str = "";
            for (int i = 0; i < md5data.Length; i++)
            {
                str += md5data[i].ToString("x").PadLeft(2, '0');
            }
            return str;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string MD5_B64(string pwd, Encoding encoding)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = encoding.GetBytes(pwd);
            byte[] md5data = md5.ComputeHash(data);
            md5.Clear();
            return Convert.ToBase64String(md5data);
        }

        public static string MD5(string str, string charset)
        {
            byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider check;
                check = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] somme = check.ComputeHash(buffer);
                string ret = "";
                foreach (byte a in somme)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("X");
                    else
                        ret += a.ToString("X");
                }
                return ret.ToLower();
            }
            catch
            {
                throw;
            }
        }
        #endregion
    }
}
